package com.neusoft.EYSystem.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.neusoft.EYSystem.po.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("getCode")
    public Result<Map<String, String>> getCode() {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        String verify = IdUtil.simpleUUID();
        //图形验证码写出，可以写出到文件，也可以写出到流
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        lineCaptcha.write(os);
        String code = lineCaptcha.getCode();
//        缓存一分钟的验证码
        redisTemplate.opsForValue().set(verify, code, Duration.ofMinutes(1));
        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>(5);
        //验证码对应的redis上的uuid
        map.put("uuid", verify);
        //图片上的验证码
        map.put("code", code);
        //将图片转换成输出流传到前端上
        map.put("img", Base64.encode(os.toByteArray()));
        return Result.ok(map);
    }
}
